// pages/sales/custom/add_group.js
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");

//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle,{

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    firstIn:true,
    isAdd:true,
    groupName:"",
    _groupName:"",
    list: [],
    openidMap:{},
    isLoading: false,
    size: 10,
    curPage: 1,
    total: 0,
    isBottom: false,
    pickerName: "全部",
    relationMap: {},
    rmMap: {},
    addMap: {},
    pickerArr: ["扫码","分享", "搜索", "交接"]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('.........*****************//////',options)
    wx.hideShareMenu();
    var ctx = this;
    ctx.setData({
      rmMap: new Map(),
      addMap: new Map(),
    });
    if (options.gId){
      ctx.setData({
        isAdd:false,
        groupId: options.gId
      });
    }
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      if(options.gId){
        ctx.findGroupManageMemberList(options.gId);
      }else{

        ctx.findGroupManageMemberList();
      }
    });
  },
  findGroupManageMemberList(groupId){
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/relationgroup/findGroupManageMemberList',
      data: {
        cusmallToken: cusmallToken,
        groupId: groupId || "",
        start: (ctx.data.curPage - 1) * ctx.data.size,
        limit: ctx.data.size,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data.ret == 0) {
          let openidMap = ctx.data.openidMap;
          if (data.model.group){
            if (ctx.data.firstIn){
              let openidArr = data.model.group.openidList.fliter(item=>item).split(",");
              for (let item of openidArr) {
                openidMap[item] = true;
              }
              ctx.setData({
                groupName: data.model.group.name,
                _groupName: data.model.group.name,
                openidMap: openidMap
              });
            }
            
          }else{
            openidMap = ctx.data.openidMap
          }
          if (data.model.relation) {
            for (let item of data.model.relation) {
              item.followSatus = (item.followTime && ctx.followTimeToTxt(item.followTime)) || "未跟进客户";
              ctx.setData({
                ['relationMap.' + item.memberId + '']: item
              });
            }

          } else {
            ctx.setData({
              relationMap: null
            })
          }

          var list = data.model.list || [];
          list = list.filter((item,index)=>{
            if(item){
              item.source = data.model.relation[index].source
            }
            return item
          })
          for (let item of list) {
            if (openidMap[item.openid]){
              item.checked = true;
            }
            item.behaviorTime = util.formatTime(new Date(ctx.data.relationMap[item.id].createTime));
            item.sourceTimeTxt = ctx.getSource(item.source);

          }

          ctx.setData({
            list: ctx.data.list.concat(list),
            total: data.model.total
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {

          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      complete() {
        ctx.setData({
          isLoading: false
        })
      }
    });
  },
  selCustomer(e){
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var checked = !ctx.data.list[idx].checked;
    var rmMap = ctx.data.rmMap;
    var addMap = ctx.data.addMap;
    var gg = new Map();
    console.log(rmMap, gg)
    if(ctx.data.isAdd){
      if (checked) {
        addMap.set(ctx.data.list[idx].id, ctx.data.list[idx].openid);
      } else {
        addMap.delete(ctx.data.list[idx].id);
      }
    }else{
      if (checked) {
        addMap.set(ctx.data.list[idx].id, ctx.data.list[idx].openid);
        rmMap.delete(ctx.data.list[idx].id);
      } else {
        addMap.delete(ctx.data.list[idx].id);
        rmMap.set(ctx.data.list[idx].id, ctx.data.list[idx].openid);
      }
    }

    ctx.setData({
      rmMap: rmMap,
      addMap: addMap,
      ["list[" + idx + "].checked"]: checked,
    })
    

  },
  groupNameInput(e){
    console.log(e);
    this.setData({
      _groupName: e.detail.value
    });
  },
  handleCommit(){
    var ctx = this;
    var groupName = ctx.data._groupName;
    if (!groupName){
      wx.showToast({
        title: '分组名称不能为空',
        icon:"none"
      });
      return;
    }

    if (ctx.data.isAdd && 0 == ctx.data.addMap.size){
      wx.showToast({
        title: '请选择分组成员',
        icon: "none"
      });
      return;
    }
    var rmMap = ctx.data.rmMap;
    var addMap = ctx.data.addMap;
    var rmListStr = [];
    var addListStr = [];
    var groupId = ctx.data.groupId || "";
    for (let value of rmMap.values()) {
      rmListStr.push(value)
    }
    for (let value of addMap.values()) {
      addListStr.push(value)
    }

    ctx.saveGroup(groupId, groupName, rmListStr.join(","), addListStr.join(","));
  },
  saveGroup(groupId, groupName, rmListStr, addListStr){
    var ctx = this;
    wx.showLoading({
      title: ' 保存中'
    });
    ctx.setData({ isLoading: true });

    
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/relationgroup/save',
      data: {
        cusmallToken: cusmallToken,
        id: groupId || "",
        name: groupName,
        rmList: rmListStr,
        addList: addListStr,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data.ret == 0) {
          wx.showToast({
            title: "保存成功",
            icon: "none"
          });
          setTimeout(function(){
            let pages = getCurrentPages();//当前页面
            let prevPage = pages[pages.length - 2];//上一页面
            prevPage.handleRefreshData();
            wx.navigateBack({
              delta: 1
            });
          },500)
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          });
        }
      },
      complete() {
        ctx.setData({
          isLoading: false
        })
      }
    });
  },
  getSource(src) {
    switch (src) {
      case 0:
        return "最后扫描";
      case 1:
        return "最后分享";
      case 2:
        return "最后搜索";
      case 3:
        return "最后交接";
      default:
        return "";
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let ctx = this;
    if (ctx.data.isLoading) {
      return;
    }
    ctx.setData({ curPage: ctx.data.curPage + 1 });
    ctx.findGroupManageMemberList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))